package com.ishare.common.service.base.impl;

import com.ishare.common.constant.RedisKey;
import com.ishare.common.service.base.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 李嘉宾
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void refreshToken(Integer uid, String token) {
        stringRedisTemplate.opsForValue().set(RedisKey.USER_TOKEN_TO_UID.addSuffix(token), uid + "", 30, TimeUnit.MINUTES);
    }

    @Override
    public void clearToken(String token) {
        stringRedisTemplate.delete(RedisKey.USER_TOKEN_TO_UID.addSuffix(token));
    }

    @Override
    public Integer getUserIdByToken(String token) {
        String cacheUid = stringRedisTemplate.opsForValue().get(RedisKey.USER_TOKEN_TO_UID.addSuffix(token));
        if (StringUtils.isEmpty(cacheUid)) {
            return null;
        }
        return Integer.parseInt(cacheUid);
    }
}
